package com.snack.system.controller;

import com.snack.common.core.constant.UserConstants;
import com.snack.common.core.utils.StringUtils;
import com.snack.common.core.web.controller.BaseController;
import com.snack.common.core.web.domain.AjaxResult;
import com.snack.common.core.web.page.TableDataInfo;
import com.snack.common.log.annotation.Log;
import com.snack.common.log.enums.BusinessType;
import com.snack.common.security.annotation.RequiresPermissions;
import com.snack.common.security.utils.SecurityUtils;
import com.snack.system.domain.TsGoodsType;
import com.snack.system.service.ITsGoodsTypeService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品类型Controller
 * 
 * @author snack
 * @date 2022-09-18
 */
@RestController
@RequestMapping("/type")
public class TsGoodsTypeController extends BaseController
{
    @Autowired
    private ITsGoodsTypeService goodsTypeService;

    /**
     * 查询商品类型列表
     */
    @RequiresPermissions("snack:type:list")
    @GetMapping("/list")
    public TableDataInfo list(TsGoodsType tsGoodsType)
    {
        startPage();
        List<TsGoodsType> list = goodsTypeService.selectList(tsGoodsType);
        return getDataTable(list);
    }

    /**
     * 查询查询设备类型列表（排除节点）
     */
    @RequiresPermissions("snack:type:edit")
    @GetMapping("/list/exclude/{goodsTypeId}")
    public AjaxResult excludeChild(@PathVariable(value = "goodsTypeId", required = false) Long goodsTypeId)
    {
        List<TsGoodsType> list = goodsTypeService.selectAllList();
        list.removeIf(f -> f.getGoodsTypeId().intValue() == goodsTypeId
                || ArrayUtils.contains(StringUtils.split(f.getAncestors(), ","), goodsTypeId + ""));
        return AjaxResult.success(list);
    }


    /**
     * 获取商品类型详细信息
     */
    @RequiresPermissions("snack:type:query")
    @GetMapping(value = "/{goodsTypeId}")
    public AjaxResult getInfo(@PathVariable("goodsTypeId") Long goodsTypeId)
    {
        return AjaxResult.success(goodsTypeService.selectTypeById(goodsTypeId));
    }

    /**
     * 获取商品类型下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect()
    {
        List<TsGoodsType> types = goodsTypeService.selectAllList();
        return AjaxResult.success(goodsTypeService.buildTreeSelect(types));
    }

    /**
     * 通过类型id查询属性列表
     * @param goodsTypeId 类型id
     * @return
     */
    @GetMapping("/goodsTypeParam/{goodsTypeId}")
    public AjaxResult getParamList(@PathVariable("goodsTypeId") Long goodsTypeId){
        return AjaxResult.success(goodsTypeService.getParamList(goodsTypeId));
    }

    /**
     * 新增商品类型
     */
    @RequiresPermissions("snack:type:add")
    @Log(title = "商品类型", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TsGoodsType goodsType)
    {
        if (UserConstants.NOT_UNIQUE.equals(goodsTypeService.checkNameUnique(goodsType)))
        {
            return AjaxResult.error("新增商品类型'" + goodsType.getTypeName() + "'失败，商品类型名称已存在");
        }
        goodsType.setCreateBy(SecurityUtils.getUsername());
        return toAjax(goodsTypeService.insert(goodsType));
    }

    /**
     * 修改商品类型
     */
    @RequiresPermissions("snack:type:edit")
    @Log(title = "商品类型", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TsGoodsType goodsType)
    {
        if (UserConstants.NOT_UNIQUE.equals(goodsTypeService.checkNameUnique(goodsType)))
        {
            return AjaxResult.error("修改商品类型'" + goodsType.getTypeName() + "'失败，商品类型名称已存在");
        }
        else if (goodsType.getGoodsTypeId().equals(goodsType.getParentId()))
        {
            return AjaxResult.error("修改商品类型'" + goodsType.getTypeName() + "'失败，上级商品类型不能是自己");
        }
        else if (StringUtils.equals(UserConstants.EXCEPTION, goodsType.getStatus())
                && goodsTypeService.selectNormalChildrenById(goodsType.getGoodsTypeId()) > 0)
        {
            return AjaxResult.error("该商品类型包含未停用的子设备类型！");
        }
        goodsType.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(goodsTypeService.update(goodsType));
    }

    /**
     * 删除商品类型
     */
    @RequiresPermissions("snack:type:remove")
    @Log(title = "商品类型", businessType = BusinessType.DELETE)
    @DeleteMapping("/{goodsTypeId}")
    public AjaxResult remove(@PathVariable Long goodsTypeId)
    {
        if (goodsTypeService.hasChildById(goodsTypeId))
        {
            return AjaxResult.error("存在下级商品类型,不允许删除");
        }
        if (goodsTypeService.checkExistData(goodsTypeId))
        {
            return AjaxResult.error("商品类型存在商品,不允许删除");
        }
        return toAjax(goodsTypeService.deleteById(goodsTypeId));
    }
}
